<?php
require_once '../inc/Citru.php'; 
session_start();

class CitruLogin {
		
	public static function getForm() {
		if(isset($_SESSION['user'])) {
			$message = CitruLogin::loggedIn();
		}

		if(isset($_POST['user'])) {
			$message = CitruLogin::loginUser();
		}

		# Create a form
		$form = '<p>'.$message.'</p>'."\n".
				'<form id="LoginModule" action="" method="post">'."\n".
				'<label for="LoginModule_user">Username:</label><br />'."\n".
				'<input class="LoginModule_user" id="LoginModule_user" name="user" type="text" value="" /><br />'."\n".
				'<label for="LoginModule_pass">Password:</label><br />'."\n".
	   			'<input class="LoginModule_pass" id="LoginModule_pass" name="pass" type="password" value="" /><br />'."\n".
	   			'<input class="LoginModule_submit" id="LoginModule_submit" type="submit" value="login" />'."\n".
	   			'</form>';

		return $form;
	}
	
	private static function loggedIn() {
		if(isset($_GET['logout'])) {
			$_SESSION['user'] = null;
			$_SESSION['hash'] = null;
			header('Location: ../');
		}
		return 'User logged in. <a href="?logout">Click to Logout</a>';
	}
	
	private static function loginUser() {
		// Check for valid usernames
		$citru = new Citru('login', '../');
		if(!preg_match('/[^A-Za-z0-9-_]+/', $_POST['user'])) {
			// Check that the username/pass exists
			if($citru->checkLogin($_POST['user'], $_POST['pass'])) {
				$_SESSION['user'] = $_POST['user'];
				$_SESSION['hash'] = sha1($_POST['pass']);
				header('Location: ../');
			}
			return 'Wrong username or password.';
		}
		return 'Invalid username.';
	}
	
}

$formData = CitruLogin::getForm();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
	<title>Citru login</title>
	
	<link rel="stylesheet" href="../css/panel.css" type="text/css" media="screen">
	
</head>
<body>
	<div id="wrap" class="narrow">
		<h1>Citru Login</h1>
		<div class="panel_module">
			<?php echo $formData; ?>
		</div>
	</div>
</body>
</html>
	